package com.demo.statemachine.d05.store;

import com.demo.statemachine.d05.formStateMachine.FormEvents;
import com.demo.statemachine.d05.formStateMachine.FormStates;
import com.demo.statemachine.d05.orderStateMachine.OrderEvents;
import com.demo.statemachine.d05.orderStateMachine.OrderStates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.data.redis.RedisStateMachineContextRepository;
import org.springframework.statemachine.data.redis.RedisStateMachinePersister;
import org.springframework.statemachine.persist.DefaultStateMachinePersister;
import org.springframework.statemachine.persist.RepositoryStateMachinePersist;
import org.springframework.statemachine.persist.StateMachinePersister;

/**
 * 状态持久化配置
 */
@Configuration
public class PersistConfig {
//------------------------ 内存存储 -------------------------
    @Autowired
    private FormInMemoryStateMachinePersist formInMemoryStateMachinePersist;
    @Autowired
    private OrderInMemoryStateMachinePersist orderInMemoryStateMachinePersist;

    @Bean(name="orderMemoryPersister")
    public StateMachinePersister<OrderStates, OrderEvents, String> orderMemoryPersister() {
        return new DefaultStateMachinePersister<>(orderInMemoryStateMachinePersist);
    }
    @Bean(name="formMemoryPersister")
    public StateMachinePersister<FormStates, FormEvents, String> formMemoryPersister() {
        return new DefaultStateMachinePersister<>(formInMemoryStateMachinePersist);
    }

//------------------------ redis存储 -------------------------
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    /**
     * 注入RedisStateMachinePersister对象
     *
     * @return
     */
    @Bean(name = "redisPersister")
    public RedisStateMachinePersister<OrderStates, OrderEvents> redisPersister() {
        return new RedisStateMachinePersister<>(redisPersist());
    }
    /**
     * 通过redisConnectionFactory创建StateMachinePersist
     *
     * @return
     */
    public StateMachinePersist<OrderStates, OrderEvents,String> redisPersist() {
        RedisStateMachineContextRepository<OrderStates, OrderEvents> repository =
                new RedisStateMachineContextRepository<>(redisConnectionFactory);
        return new RepositoryStateMachinePersist<>(repository);
    }
}
